<template>
  <view class="search-container">
    <tn-nav-bar fixed alpha customBack>
      <view slot="back" class='tn-custom-nav-bar__back' @click="goHome">
        <view class="nav-back-btn">
          <text class='icon tn-icon-home-smile'></text>
        </view>
      </view>
    </tn-nav-bar>
    <view class="container" :style="{paddingTop: vuex_custom_bar_height + 'px'}">
        <!-- 搜索栏 -->
      <view class="search-box">
        <view class="search-input-wrap">
          <view class="search-icon">
            <text class="tn-icon-search"></text>
          </view>
          <tn-input
            v-model="queryParams.title"
            type="text"
            placeholder="请输入搜索资源"
            :border="false"
            width="100%"
            @confirm="handleSearch"
            class="search-input"
          />
        </view>
        
        <view class="search-btn-wrap">
          <view class="search-btn-large" @click="handleSearch">搜索</view>
        </view>
      </view>
      
      <!-- 资源列表 -->
      <scroll-view 
        scroll-y 
        class="resource-scroll"
        :style="{height: 'calc(100vh - ' + (vuex_custom_bar_height + 200) + 'px)'}" 
        refresher-enabled
        :refresher-triggered="isRefreshing"
        @refresherrefresh="onRefresh"
        @scrolltolower="loadMore"
      >
        <view class="resource-list">
          <view 
            class="resource-item"
            v-for="(item, index) in resourceList" 
            :key="index"
          >
            <!-- 图片预览 -->
            <view class="resource-image" @tap="previewImage(item.cover_image)">
              <image 
                :src="item.cover_image" 
                mode="widthFix"
              />
            </view>
            <!-- 底部信息栏 -->
            <view class="resource-footer">
              <text class="resource-title">{{item.title}}</text>
              <view class="download-btn">
                <tn-button
                  backgroundColor="#4080FF"
                  fontColor="#FFFFFF"
                  size="sm"
                  @click="showResourceModalManager(item)"
                >
                  获取资源
                </tn-button>
              </view>
            </view>
          </view>
        </view>
        <!-- 底部加载状态 -->
        <view class="load-more" v-if="resourceList.length > 0">
          <text class="load-more-text">{{ hasMore ? '加载中...' : '暂无更多资源' }}</text>
        </view>
      </scroll-view>
      <!-- 资源获取弹窗 -->
      <tn-modal v-model="showResourceModal" :custom="true" @cancel="closeResourceModal">
        <view class="custom-modal-content">
          <view class="modal-icon">
            <text class="tn-icon tn-icon-about-fill"></text>
          </view>
          <view class="modal-title"><text>{{currentResource.title}}</text></view>
          <view class="modal-info">
            <view class="info-label">下载地址</view>
            <view class="info-content">{{currentResource.wangpan_link}}</view>
          </view>
          <view class="modal-info">
            <view class="info-label">资源说明</view>
            <view class="info-content">可以复制链接到浏览器下载或直接点击下载。</view>
          </view>
          <view class="modal-buttons">
            <view class="modal-button" @click="copyToClipboard(currentResource.wangpan_link)">
              <text class="button-icon tn-icon-copy"></text>
              <text class="button-text">复制链接</text>
            </view>
          </view>
        </view>
      </tn-modal>
      <!-- 激励视频 -->
      			<!-- <ad-rewarded-video ref="adRewardedVideo" adpid="1392842665" :preload="false" :loadnext="false" :disabled="true"
				v-slot:default="{error}" @load="onadload" @close="onadclose" @error="onaderror">
				<view class="ad-error" v-if="error">{{error}}</view>
			</ad-rewarded-video> -->
    </view>
    
  </view>
</template>

<script>
import { getResourceList  } from '@/api/resource.js'
export default {
  data() {
    return {
      resourceList: [],
      queryParams: {
        type: '',
        title: '',
        id: '',
        page: 1,
        pageSize: 10
      },
      submitLoading: false,
      showResourceModal: false,
      currentResource: null,
      pagination: {
        total: 0,
        current: 1
      },
      isRefreshing: false,
      hasMore: true
    }
  },
  onLoad(options) {
    console.log('options', options)
    // 设置查询参数
    if (options) {
      if (options.type) this.queryParams.type = options.type;
      if (options.title) {
        this.queryParams.title = options.title;
      }
      if (options.id) {
        this.queryParams.id = options.id;
        this.queryParams.title = ''
      }
    }
    
    // 初始化加载第一页数据
    this.loadResourceList();
  },
  mounted() {
    // 页面挂载完成后的其他初始化操作（如果需要）
  },
  methods: {
    // 返回首页
    goHome() {
      uni.navigateTo({
        url: '/pages/index'
      })
    },
    // 加载资源列表数据
    async loadResourceList() {
      try {
        const params = {
          ...this.queryParams,
        }
        const res = await getResourceList(params)
        if (res && res.data) {
          // 如果是第一页，直接赋值；如果是加载更多，则追加数据
          if (this.queryParams.page === 1) {
            this.resourceList = res.data.list
          } else {
            this.resourceList = [...this.resourceList, ...res.data.list]
          }
          this.pagination = {
            total: res.data.pagination.total,
            current: res.data.pagination.current
          }
          // 判断是否还有更多数据
          this.hasMore = this.resourceList.length < this.pagination.total
        }
      } catch (error) {
        console.error('获取资源列表失败:', error)
        uni.showToast({
          title: '获取资源列表失败',
          icon: 'none'
        })
      } finally {
        this.isRefreshing = false
      }
    },
    // 加载更多数据
    async loadMore() {
      if (!this.hasMore || this.isRefreshing) return
      this.queryParams.page++
      await this.loadResourceList()
    },
    // 下拉刷新处理
    async onRefresh() {
      if (this.isRefreshing) return
      this.isRefreshing = true
      this.queryParams.page = 1
      await this.loadResourceList()
    },
    // 搜索处理
    handleSearch() {
      this.resourceList = []
      this.queryParams.page = 1
			this.queryParams.id = ''
      this.loadResourceList()
    },
    
    // 预览图片
    previewImage(url) {
      uni.previewImage({
        urls: [url],
        current: url
      })
    },
    
    // 显示资源弹窗
    showResourceModalManager(item) {
      uni.showModal({
        title: '恳请小主爸爸看个广告吧',
        content: '收集不易, 看完广告资源就加载好了',
        confirmText: '确认',
        confirmColor: '#E83A30',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            if(this.submitLoading) {
              return
            }
            this.currentResource = item
            this.openResourceModal(item)
            // this.$refs.adRewardedVideo.show();
          }
        }
      });
    },
    // 激励视频
    onadload(e) {
      this.submitLoading = false;
      console.log('广告数据加载成功');
    },
    onadclose(e) {
      const detail = e.detail
      // 用户点击了【关闭广告】按钮
      if (detail && detail.isEnded) {
        // 正常播放结束
        console.log("onClose " + detail.isEnded);
        this.openResourceModal()
      } else {
        // 播放中途退出
        console.log("onClose " + detail.isEnded);
      }
    },
    onaderror(e) {
      // 广告加载失败
      console.log(e.detail);
      this.submitLoading = false;
    },
    // 打开资源弹窗
    openResourceModal() {
      this.showResourceModal = true;
    },
    // 关闭资源弹窗
    closeResourceModal() {
      this.showResourceModal = false;
    },
    // 复制到剪切板
    copyToClipboard(url) {
      uni.setClipboardData({
        data: url,
        success: () => {
          uni.showToast({
            title: '链接已复制',
            icon: 'success'
          });
        }
      });
    },
  }
}
</script>

<style lang="scss">
.search-container {
  padding: 20rpx;
  
  .tn-custom-nav-bar__back {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    .nav-back-btn {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(255, 255, 255, 0.85);
      border-radius: 50%;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
      
      .icon {
        font-size: 42rpx;
        color: #333;
      }
      
      &:active {
        transform: scale(0.95);
      }
    }
  }
  .search-box {
    position: sticky;
    top: 0;
    z-index: 100;
    background-color: #fff;
    padding: 30rpx;
    .search-input-wrap {
      background-color: #F7F8FA;
      border-radius: 12rpx;
      margin-bottom: 20rpx;
      display: flex;
      align-items: center;
      padding: 0 24rpx;
      height: 88rpx;
      .search-icon {
        padding-right: 20rpx;
        color: #666;
        font-size: 36rpx;
      }
      .search-input {
        flex: 1;
        /deep/ .tn-input__input {
          background-color: transparent;
          height: 88rpx;
          font-size: 28rpx;
          padding: 0;
        }
      }
    }
    .search-btn-wrap {
      .search-btn-large {
        width: 100%;
        height: 88rpx;
        line-height: 88rpx;
        text-align: center;
        border-radius: 44rpx;
        font-size: 32rpx;
        font-weight: 500;
        letter-spacing: 2rpx;
        background: #4080FF;
        color: #fff;
        &:active {
          transform: scale(0.98);
          opacity: 0.9;
        }
      }
    }
  }
  .resource-scroll {
    width: 100%;
    .resource-list {
      padding: 20rpx;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      .resource-item {
        width: calc(50% - 10rpx);
        background-color: #fff;
        border-radius: 12rpx;
        margin-bottom: 20rpx;
        box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
        overflow: hidden;
        .resource-image {
          width: 100%;
          height: auto;
          image {
            width: 100%;
            height: auto;
          }
        }
        .resource-footer {
          padding: 16rpx;
          display: flex;
          flex-direction: column;
          .resource-title {
            font-size: 28rpx;
            color: #333;
            margin-right: 16rpx;
            // 文字超出显示省略号
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-bottom: 10rpx;
          }
          .download-btn {
            display: flex;
            flex-direction: row-reverse;
          }
        }
      }
    }
  }
  .custom-modal-content {
    padding: 30rpx;
    .modal-icon {
      text-align: center;
      margin-bottom: 20rpx;
      .tn-icon {
        font-size: 80rpx;
        color: #4080FF;
        animation: iconFloat 2s ease-in-out infinite;
      }
    }
    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      text-align: center;
      margin-bottom: 30rpx;
      padding: 0 20rpx;
    }
    .modal-info {
      margin-bottom: 20rpx;
      background-color: #F8F9FC;
      border-radius: 12rpx;
      padding: 20rpx;
      .info-label {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 10rpx;
      }
      .info-content {
        font-size: 28rpx;
        color: #333;
        word-break: break-all;
      }
    }
    .modal-buttons {
      margin-top: 30rpx;
      .modal-button {
        background-color: #4080FF;
        height: 88rpx;
        border-radius: 44rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
        .button-icon {
          font-size: 32rpx;
          color: #FFFFFF;
          margin-right: 10rpx;
        }
        .button-text {
          font-size: 30rpx;
          color: #FFFFFF;
          font-weight: 500;
        }
        &:active {
          transform: scale(0.98);
          opacity: 0.9;
        }
      }
    }
  }
}
.load-more {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 0;
  
  .load-more-text {
    font-size: 28rpx;
    color: #999;
  }
}
</style>